package com.vcredit.creditcat.web.app;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import com.vcredit.creditcat.api.*;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.vo.*;
import com.vcredit.framework.util.JacksonUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.common.utils.IOUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.vcredit.creditcat.dto.shareInfo.ShareContext4VM;
import com.vcredit.creditcat.dto.shareInfo.ShareInfo;
import com.vcredit.creditcat.enumtype.SendSmsTypeEnum;
import com.vcredit.creditcat.interceptor.SendMessageException;
import com.vcredit.creditcat.model.AppVersion;
import com.vcredit.creditcat.model.Banner;
import com.vcredit.creditcat.util.EnumExtUtil;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.MD5Util;

/**
 * 公共服务的Controller
 * @author zhaoqi01
 */
@RestController
public class CommonController extends BaseCreditCatController {
  @Reference(version = "1.0")
  private IAppVersionManager appVersionManager;

  @Reference(version = "1.0")
  private IBannerManager bannerService;

  @Reference(version = "1.0")
  private ISMSMessageManager SMSmessageManager;

  @Reference(version = "1.0")
  private IAuthorizeManager authorizeManager;

  @Reference(version = "1.0")
  private IShareInfoManager shareInfoManager;

  @Reference(version = "1.0")
  private IClickLogManager clickLogManager;

  @Reference(version = "1.0")
  private IRegionalismManager regionalismManager;

  @Reference(version = "1.0")
  private IAppSwitchManager appSwitchManager;


  @Value("${sms.send.key}")
  private String smsKey;

  /**
   * 获取APP的最新版本信息  内容包括：最新安装包信息和数据字典的最新版本号
   *
   * @return
   * @throws Exception
   * @author zhaoqi01
   */
  @Log
  @RequestMapping(value = "/version/newVersion")
  public JsonResult<VersionVo> getNewVersion(HttpServletRequest request) throws Exception {
	  
	BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));  
	String body = IOUtils.read(reader);
	String appDesc=null;
    if(StringUtils.isNotBlank(body)){
      Map<String, Object> map = JacksonUtil.Json2Map(body);
      appDesc = (String)map.get("appDesc");
    }
    AppVersion appVersion = appVersionManager.getAppVersion(appDesc);
    VersionInfo androidVI =
            new VersionInfo(appVersion.getDownloadUrlAndroid(), appVersion.getVersionNameAndroid(),
                    appVersion.getVersionCodeAndroid(), appVersion.getVersionCodeEnum(),
                    appVersion.getDescriptionAndroid(), appVersion.getAppSizeAndroid(),appVersion.getSwitchAndroid());
    VersionInfo iosVI =
            new VersionInfo(appVersion.getDownloadUrlIos(), appVersion.getVersionNameIos(),
                    appVersion.getVersionCodeIos(), appVersion.getVersionCodeEnum(),
                    appVersion.getDescriptionIos(), appVersion.getAppSizeIos(),appVersion.getSwitchIos());
    Long newSpecial=appVersionManager.findNewFastProduct(appDesc);
    Map<String,Object> updateFlag=new HashMap<>();
    if(newSpecial==null){
      updateFlag.put("product",0);
    }else{
      updateFlag.put("product",Integer.valueOf(newSpecial.toString()));
    }
    VersionVo result=new VersionVo();
    result.setAndroid(androidVI);
    result.setIos(iosVI);
    result.setUpdateFlag(updateFlag);
    return JsonResult.SuccessResponse(result);
  }

  /**
   * 发送短信验证码
   *
   * @param smsParam
   * @param request
   * @return
   * @throws Exception
   * @author zhaoqi01
   */
  @SuppressWarnings("rawtypes")
  @Log
  @RequestMapping(value = "/sms/vcode")
  public JsonResult sendSMS(@RequestBody @Valid SmsParam smsParam, HttpServletRequest request)
          throws Exception {
    String signature = smsParam.getSignature();
    String mobile = smsParam.getMobileNo();
    SendSmsTypeEnum accountType =
            EnumExtUtil.getEnumOnValue(SendSmsTypeEnum.class,
                    String.valueOf(smsParam.getBusinessType()), "code");
    // 判断序列号
    String key = MD5Util.md5(MD5Util.md5_16(mobile) + smsKey);
    if (!key.equals(signature)) {
      throw new SendMessageException("发送短信错误");
    }
    // 1、登录 2、实名认证 3、校验银行卡
    Integer businessType = null;
    switch (accountType) {
      case Login:
        businessType = SendSmsTypeEnum.Login.getCode();
        break;
      case BindMobile:
        businessType = SendSmsTypeEnum.BindMobile.getCode();
        break;
      case BindBankCard:
        businessType = SendSmsTypeEnum.BindBankCard.getCode();
        break;
      default:
        throw new SendMessageException("未知的消息类型");
    }
    String code = createVerifyCode(request, mobile, businessType);
    SMSmessageManager.sendVerificationCode(mobile, code, businessType);
    if(businessType .equals(SendSmsTypeEnum.Login.getCode())){
      //调用登录产品预检
      authorizeManager.doLoginPreview(mobile);
    }
    return JsonResult.SuccessResponse(null);
  }

  /**
   * 根据广告类型 获取广告列表
   *
   * @param loginParam
   * @param request
   * @return
   * @author zhaoqi01
   */
  @RequestMapping("/banner/list")
  public JsonResult<BannerResponseVo> queryBanner(@RequestBody @Valid Map<String,String> loginParam,
                                                  HttpServletRequest request) {
    String bannerKind=loginParam.get("bannerKind");
    String appDesc=loginParam.get("appDesc");
    List<Banner> BannerList = bannerService.queryBannerByKind(bannerKind,appDesc);
    List<BannerVo> banners = new ArrayList<BannerVo>();
    for (Banner Banner : BannerList) {
      banners.add(new BannerVo(Banner.getBannerImg(), Banner.getBannerUrl()));
    }
    return JsonResult.SuccessResponse(new BannerResponseVo(banners));
  }

  /**
   * 获取分享信息
   *
   * @param request
   * @return
   * @throws Exception
   */
  @Log
  @RequestMapping(value = "/getShareInfo")
  public JsonResult<ShareInfo> getShareInfo(@RequestBody ShareParam param,
      HttpServletRequest request) throws Exception {
    //Cust currentCust = super.getCust(request);
    long custId = -1;
    ShareInfo shareInfo =
        shareInfoManager.processShareInfo(new ShareContext4VM<>(param.getShareCode(), param
            .getShareType(), custId, null));
    return JsonResult.SuccessResponse(shareInfo);
  }
  /**
   * 记录点击日志
   * @param clickLogParam
   * @param request
   * @return
   */
  @Log
  @RequestMapping(value="/gather/clickLog")
  public JsonResult recordClickLog(@RequestBody @Valid ClickLogParam clickLogParam,HttpServletRequest request){
    Cust cust=getCust(request);
    clickLogManager.recordClickLog(cust.getCustId(),clickLogParam.getKeyPoint(),clickLogParam.getKeyData().toString());
    return JsonResult.SuccessResponse(null);
  }

  /**
   * 获取所有行政区划
   * @param request
   * @return
   * @throws Exception
   */
  @Log
  @RequestMapping(value="/regionalism/getAllRegionalisms")
  public JsonResult getAllRegionalisms(@RequestBody @Valid RegionalismParamVo param, HttpServletRequest request)throws Exception{
    Map<String,Object> map=regionalismManager.getAllRegionalisms(param.getChangeStatus());
    return JsonResult.SuccessResponse(map);
  }
}
